package controller;

import Dto.GoodsDto;
import dao.impl.OrderDAOImpl;
import model.Goods;
import model.Order;
import model.common.Msg;
import utils.BeanUtil;
import utils.JSONUtil;

import java.util.List;

public class OrderController extends BaseController{

    private final OrderDAOImpl orderDAO;

    public OrderController(){
        orderDAO = new OrderDAOImpl();
    }
    //新增订单
    public void addOrder2Db(Order order)
    {
        orderDAO.addOrder(order);

    }

    //查询订单
    public String findOrder()
    {
        Msg msg = new Msg();
        //异常处理
        try {
            //1获取所有订单的对象列表
            List<Order> orderList = orderDAO.findOrder();
            //2.将商品对象列表转换成字符串并返回
            msg.setObj(orderList);
            msg.setType(Msg.SUCCESS);

            String result = JSONUtil.entity2JSON(msg);
            //记录日志
            log.info("获取订单列表");
            //响应消息到客户端
            return result;
        }catch (Exception e)
        {
            msg.setType(Msg.FAIL);
            msg.setMsg("获取订单列表失败，服务器异常");
            //4.记录日志
            log.error("获取订单列表失败："+e.getMessage());
        }
        return JSONUtil.entity2JSON(msg);
    }

    //修改订单
    public String updateOrder(Order order)
    {
        return null;
    }

    //删除订单
    public void deleteOrder(String id)
    {
        orderDAO.deleteByOrderId(id);
    }

    // 写入订单详情
    public void addOrderDetail(Order order, Goods goods, int goodNumber)  {
        GoodsDto goodsDto = new GoodsDto();
        BeanUtil.copyProperties(goodsDto, goods);
        goodsDto.setNum(goodNumber);
        orderDAO.addOrderDetail(order, goodsDto);
    }

    // 查询当前用户的订单
    public String findMyOrder(String id){
        Msg msg = new Msg();
        //异常处理
        try {
            //1获取所有订单的对象列表
            List<Order> orderMyList = orderDAO.findMyOrder(id);
            //2.将商品对象列表转换成字符串并返回
            msg.setObj(orderMyList);
            msg.setType(Msg.SUCCESS);

            String result = JSONUtil.entity2JSON(msg);
            //记录日志
            log.info("获取当前用户订单列表");
            //响应消息到客户端
            return result;
        }catch (Exception e)
        {
            msg.setType(Msg.FAIL);
            msg.setMsg("获取订单列表失败，服务器异常");
            //4.记录日志
            log.error("获取订单列表失败："+e.getMessage());
        }
        return JSONUtil.entity2JSON(msg);
    }

}
